<template>
  <div>
    <div v-if="userInfo" class="entry_check_wrap gl_clear">
      <van-button :loading="checkEntryBtnLoading" type="info" size="small" block @click="getEntryAndSubstationList">点击检测，获取项目</van-button>
      <div class="individual_check_wrap gl_fl">
        <span class="gl_mr_10">{{ userInfo.name }}</span>
        <span class="gl_mr_10">{{ dictGenderMap[userInfo.genderCode] ? dictGenderMap[userInfo.genderCode].value : '' }}</span>
        <span>{{ userInfo.birthDate ? userInfo.birthDate.slice(0, 10) : '' }}</span>
      </div>
    </div>

    <div v-if="entryList.length" class="individual_list_wrap">

      <div v-if="gameInfo.isFinal && substationList.length" class="event_group">
        <div class="event_title">赛区选择</div>
        <div class="event_list">
          <van-radio-group v-model="activeSubstation">
            <van-radio v-for="(item, index) in substationList" :key="index" class="event_item" :name="item.id">{{ item.competitionName }}</van-radio>
          </van-radio-group>
        </div>
      </div>

      <div v-for="(item, index) in entryShowData" :key="index" class="event_group">
        <div class="event_title">{{ item.name }}</div>
        <div class="event_list">
          <van-checkbox-group v-model="entryCheckGroupData[item.categoryId]" :max="item.maxEntry">
            <van-checkbox v-for="(jtem, jndex) in item.children" :key="jndex" icon-size="16px" class="event_item" shape="square" :name="jtem.id" border>
              <span>{{ jtem.eventGroupName }}{{ jtem.eventShortName }}</span>
            </van-checkbox>
          </van-checkbox-group>
        </div>
      </div>
    </div>

    <div v-else class="individual_list_noData">
      <p>请检测并获取项目</p>
    </div>

    <van-row gutter="10" class="bottom_btn_position">
      <van-col :span="8">
        <van-button type="default" block @click="clickPrevStep()">上一步</van-button>
      </van-col>
      <van-col :span="8">
        <van-button type="info" block :loading="submitLoading" @click="clickSubmit()">提交报名</van-button>
      </van-col>
      <van-col :span="8">
        <van-button type="info" block @click="clickGoConfirmEntry()">已报项目</van-button>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import {
  api_POST_EventsManagementEntryQueryEventsToEntryForRegisters, // 1-获取已存在人员可报的赛事项目列表
  api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters // 0-获取已存在人员联赛决赛代表的分站赛赛事列表
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementGetEntryEventsInput // 1-获取已存在人员可报的赛事项目列表
} from '@/lib/form/game/swaggerForm';

export default {
  props: {
    submitLoading: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    dict: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      activeSubstation: '',
      substationList: [],
      entryVO: new SiSTKWEventsManagementGetEntryEventsInput(), // 1-获取已存在人员可报的赛事项目列表
      entryList: [], // 原始的报项列表
      entryShowData: {}, // 处理后用于页面显示的报项数据
      entryCheckGroupData: {}, // 根据报项数据复选框数据
      checkEntryBtnLoading: false
    };
  },
  computed: {
    dictGenderMap() {
      const _map = {};
      this.dict.gender.forEach(item => {
        _map[item.code] = item;
      });
      return _map;
    }
  },
  methods: {
    getEntryAndSubstationList () {
      if (this.gameInfo.isFinal) {
        this.getSubstationList({
          competitionId: this.gameInfo.id,
          registerId: this.checkedMember.id,
          hasEntriedEvent: true
        });
      }
      this.checkEntry();
    },
    // 获取已存在人员联赛决赛代表的分站赛赛事列表
    getSubstationList (vo) {
      api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters(vo)
        .then(
          res => {
            this.substationList = res || [];
            const _findResult = res.find(item => item.hasUsed);
            this.activeSubstation = _findResult ? _findResult.id : '';
          }
        )
        .catch(
          error => {
            this.$toast({ type: 'fail', message: `获取分站列表失败 ${error.error.message}` });
          }
        );
    },
    // 检测报项信息
    checkEntry () {
      if (this.userInfo.id) {
        this.checkEntryBtnLoading = true;
        this.entryVO.competitionId = this.gameInfo.id;
        this.entryVO.registerId = this.requiredIdData.registerId;
        this.entryVO.delegationId = null; // 个人报名不需要 delegationId
        this.entryVO.hasEntriedEvent = true;
        api_POST_EventsManagementEntryQueryEventsToEntryForRegisters(this.entryVO)
          .then(
            res => {
              this.checkEntryBtnLoading = false;
              if (res.length) {
                this.entryList = res;
                this.entryCheckGroupData = {};
                this.entryShowData = this.formatEntryShowData(res);
              } else {
                this.$toast.fail(`没有检测到可以报名的项目`);
              }
            }
          )
          .catch(
            error => {
              this.checkEntryBtnLoading = false;
              this.$toast.success(`获取人员可报的赛事项目列表失败 ${error.error.message}`);
            }
          );
      }
    },
    // 处理报项显示数据
    formatEntryShowData (list) {
      const _returnData = {};
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        item.$categoryId = item.eventCategoryId;
        if (_returnData[item.$categoryId]) {
          _returnData[item.$categoryId].children.push(item);
        } else {
          _returnData[item.$categoryId] = {
            categoryId: item.$categoryId,
            name: item.eventCategoryName,
            maxEntry: item.categoryMaxEntry,
            children: [item]
          };
          // 处理复选框数据
          this.formatEntryShowDataCheckbox(item.$categoryId);
        }
        // 报了这个项目
        if (item.athleteHasEntried) {
          this.entryCheckGroupData[item.$categoryId].push(item.id);
        }
      }
      // 排序
      for (const k in _returnData) {
        const ktem = _returnData[k];
        ktem.children.sort((a, b) => a.eventShortName - b.eventShortName);
      }
      return _returnData;
    },
    // 处理报项显示数据的复选框
    formatEntryShowDataCheckbox (categoryId) {
      if (categoryId in this.entryCheckGroupData) {
        return;
      }
      this.$set(this.entryCheckGroupData, categoryId, []);
    },
    // 点击提交报名
    clickSubmit () {
      let _eventIds = [];
      for (const k in this.entryCheckGroupData) {
        const ktem = this.entryCheckGroupData[k];
        _eventIds = _eventIds.concat(ktem);
      }
      // emit
      if (_eventIds.length) {
        this.$emit(
          'onSubmitIndividualEntry',
          {
            competitionId: this.entryVO.competitionId,
            eventIds: _eventIds,
            delegationId: this.requiredIdData.delegationId,
            registerId: this.entryVO.registerId,
            entrySubstationId: this.activeSubstation
          },
          this.entryList
        );
      } else {
        this.$toast.fail(`请选择要报名的项目`);
      }
    },
    clickGoConfirmEntry () {
      this.$emit('goConfirmEntry');
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    }
  }
};
</script>

<style lang="scss" scoped>
.entry_check_wrap {
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.10);
  margin-bottom: 20px;
  overflow: hidden;
}
.individual_check_wrap {
  box-sizing: border-box;
  width: 100%;
  height: 30px;
  text-align: center;
  line-height: 28px;
  font-size: 14px;
  color: #353434;
}

.individual_list_wrap {
  padding: 10px 0;
  min-height: 360px;
  box-sizing: border-box;
}
.event_group {
  margin-bottom: 20px;
}
.event_title {
  position: relative;
  height: 20px;
  font-size: 16px;
  line-height: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
.event_list {
  padding: 10px 20px;
  padding-left: 20px;
  background: #ffffff;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.10);
}
.event_item {
  font-size: 14px;
  margin-bottom: 10px;
}
.event_item:last-child {
  margin-bottom: 0;
}
.individual_list_noData {
  padding: 140px 0px 220px;
  text-align: center;
  font-size: 14px;
  color: #c1c1c1;
}
.checkEntry_btn {
  width: 180px;
}
</style>
